package cn.spiral.core.permisson.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import cn.spiral.core.permisson.PermissonCheck;
import cn.spiral.role.entity.Role;
import cn.spiral.role.entity.RolePrivilege;
import cn.spiral.user.entity.User;
import cn.spiral.user.entity.UserRole;
import cn.spiral.user.service.UserService;

public class PermissionCheckImpl implements PermissonCheck{

	//用配置的方式，将PermissionCheckImpl交由SpringIOC托管
	
	//注解形式注入userService
	@Autowired
	private UserService userService;
	
	@Override
	public boolean isAccessible(User user, String code) {

		List<UserRole> list=user.getUserRoles();
		//如果用户角色为空，再查一次数据库，尝试更新一下角色权限
		if(list==null){
			list = userService.getUserRolesByUserId(user.getId());
		}
		if(list != null && list.size()>0){
			for(UserRole ur: list){
				Role role = ur.getId().getRole();
				for(RolePrivilege rp: role.getRolePrivileges()){
					//对比是否有code对应的权限
					if(code.equals(rp.getId().getCode())){
						//找到相等，说明明有权限，返回true
						return true;
					}
				}
			}
		}
		return false;
	}

	
}
